package reflect;

import pojo.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Scanner;

/**
* 使用反射机制调用方法
* */
public class ReflectDemo6 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Person p = new Person();
        p.sayHello();
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入类名:");
        String className = scanner.nextLine();
        System.out.println("请输入方法名:");
        String methodName = scanner.nextLine();
        Class cls = Class.forName(className);
        Object o = cls.newInstance();//Person o = new Person()
        //获取要调用的方法(仅仅只传入方法名,是获取该无参方法)
        Method method = cls.getMethod(methodName);//表示的Person中的成员方法sayGoodBye()
        //调用获取的方法
        //调用的方法.invoke(调用方法的对象)
        method.invoke(o);//o.sayGoodBye()
    }
}
